package com.cloudfun.campusshare.common.interceptor;

import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;
import org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author : zhangyongjie
 * @version : 1.0
 * @createTime : 2021/3/1 9:35
 * @description :
 */

@Configuration
public class ConfigureUrlEncoderResolver {


    private final RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    public ConfigureUrlEncoderResolver(RequestMappingHandlerAdapter requestMappingHandlerAdapter){
        this.requestMappingHandlerAdapter = requestMappingHandlerAdapter;
    }


    @PostConstruct
    private void addUrlEncoderResolver(){
        List<HandlerMethodArgumentResolver> argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers();
        List<HandlerMethodArgumentResolver> list = Lists.newArrayList();
        list.addAll(argumentResolvers);
        list.add(getUrlEncodeArgumentResolver(argumentResolvers));
        requestMappingHandlerAdapter.setArgumentResolvers(list);
    }

    private UrlEncodeArgumentResolver getUrlEncodeArgumentResolver(List<HandlerMethodArgumentResolver> argumentResolvers){

        RequestResponseBodyMethodProcessor requestResponseBodyMethodProcessor = null;
        ServletModelAttributeMethodProcessor servletModelAttributeMethodProcessor = null;

        for(HandlerMethodArgumentResolver argumentResolver:argumentResolvers){
            if(requestResponseBodyMethodProcessor != null && servletModelAttributeMethodProcessor != null){
                break;
            }

            if(argumentResolver instanceof RequestResponseBodyMethodProcessor){
                requestResponseBodyMethodProcessor = (RequestResponseBodyMethodProcessor) argumentResolver;
                continue;
            }

            if(argumentResolver instanceof ServletModelAttributeMethodProcessor){
                servletModelAttributeMethodProcessor = ((ServletModelAttributeMethodProcessor) argumentResolver);
            }

        }

        if (requestResponseBodyMethodProcessor == null || servletModelAttributeMethodProcessor == null) {
            throw new RuntimeException("requestResponseBodyMethodProcessor and "
                    + " servletModelAttributeMethodProcessor must not be null!");
        }

        return new UrlEncodeArgumentResolver(requestResponseBodyMethodProcessor,servletModelAttributeMethodProcessor);
    }
}
